<style lang="scss" rel="stylesheet/scss">
    .j-img-video-href {
        .add-item {
            display: flex;
            padding: 1.5rem 0;
            .item {
                flex:1;
                text-align: center;
                .iconfont {
                    margin-bottom: 0.7rem;
                    font-size: 2.5rem;
                    &.color-select {
                        color: #4DCC01;
                    }
                }
                .my-input {
                    position: relative;
                    .input-hide {
                        position: absolute;
                        top: 0;
                        right: 0;
                        bottom: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        opacity: 0;
                        cursor: pointer;
                    }
                }
            }
        }
        .img-list {
            text-align: left;
            margin: 0 3%;
            .img-item {
                display: inline-block;
                width: 32%;
                position: relative;
                margin-top: 0.5rem;
                margin-right: 2%;
                &:nth-child(3n) {
                    margin-right: 0;
                }
                .del {
                    position: absolute;
                    top: -10%;
                    right: -6%;
                    font-size: 1.4rem;
                }
                img {
                    width: 100%;
                    height: 5rem;
                }
            }
        }
        .show-video {
            padding: 0.5rem;
            text-align: center;
            button {
                margin-top: 1rem;
                line-height: 35px;
                height: 35px;
            }
        }
    }
</style>
<template>
    <div class="j-img-video-href">
        <div class="add-item">
            <div class="item">
                <!-- <van-uploader :after-read="onReadImg" accept="image/*" multiple>
                    <p class="iconfont icon-tupian font-normal-light"></p>
                    <p class="font-small font-normal-light">添加图片</p>
                </van-uploader> -->
                <div class="my-input" @click="addimg">
                    <p class="iconfont icon-tupian font-normal-light"></p>
                    <p class="font-small font-normal-light">添加图片</p>
                </div>
            </div>
            <div class="item">
                <div class="my-input">
                    <p class="iconfont icon-video font-normal-light" :class="{'color-select': hasvideo}"></p>
                    <p class="font-small font-normal-light">{{hasvideo? '修改': '添加'}}视频</p>
                    <input class="input-hide" type="file" id="file" @change="change" accept="video/*">
                </div>
            </div>
            <div class="item" @click="() => {dialogShow = true; showVideoDiv.show = false}">
                <p class="iconfont icon-lianjie font-normal-light" :class="{'color-select': haslink}"></p>
                <p class="font-small font-normal-light">{{haslink? '修改': '添加'}}链接</p>
            </div>
        </div>
        <van-progress :percentage="videoprogress.num" v-if="videoprogress.show" color="#4DCC01"/>
        <div class="show-video" v-if="showVideoDiv.show">
            <video id="video" controls style="width:100%;max-height:200px;" :poster="posterimg">
                <source :src="showVideoDiv.file">
            </video>
        </div>
        <ul class="img-list" v-if="imglist && imglist.length > 0">
            <li class="img-item" v-for="(item, index) in imglist" :key="index">
                <img :src="item.base" alt="">
                <span class="iconfont icon-shanchu1 font-zhu del" @click="removeimg(index)"></span>
            </li>
        </ul>
        <j-add-href v-if="dialogShow" @submit="addHref"></j-add-href>
    </div>
</template>

<script>
    import jAddHref from "components/Dialog/AddHref"
    import * as toolsUtils from 'utils/toolsUtils'
    // import * as aliyunService from 'services/aliyunService'
    import * as typeUtils from 'utils/typeUtils'
    import wx from 'weixin-js-sdk'
    import axios from 'axios';
    var uploadAuth = ''
    var uploadAddress = '' 
    var videoId = ''
    var _videoUploadSuccess = {
        ok: false,
        uploadInfo: {}
    }
    var _uploadprogress = 0
    const uploader = new AliyunUpload.Vod({
        //分片大小默认1M，不能小于100K
        partSize: 1048576,
        //并行上传分片个数，默认5
        parallel: 5,
        //网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        //网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        'onUploadstarted': function(uploadInfo) {
            // alert('开始上传')
            console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
            //上传方式1, 需要根据uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress，如果videoId有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
            uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId);
        },
        // 文件上传成功
        'onUploadSucceed': function(uploadInfo) {
            _videoUploadSuccess.ok = true
            _videoUploadSuccess.uploadInfo = uploadInfo
            console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
        },
        // 文件上传失败
        'onUploadFailed': function(uploadInfo, code, message) {
            console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
        },
        // 文件上传进度，单位：字节
        'onUploadProgress': function(uploadInfo, totalSize, loadedPercent) {
            _uploadprogress = Math.ceil(loadedPercent * 100)
            console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(loadedPercent * 100) + "%");
        },
        // 上传凭证超时
        'onUploadTokenExpired': function(uploadInfo) {
            console.console.log("onUploadTokenExpired");
            //上传方式1  实现时，根据uploadInfo.videoId调用刷新视频上传凭证接口重新获取UploadAuth
            uploader.resumeUploadWithAuth(uploadAuth);
            // 上传方式2 实现时，从新获取STS临时账号用于恢复上传
            // uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken, expireTime);
        },
        //全部文件上传结束
        'onUploadEnd': function(uploadInfo) {
            console.log("onUploadEnd: uploaded all the files");
        }
    });
    const userData = '{"Vod":{"UserData":{"IsShowWaterMark":"false","Priority":"7"}}}'
    // const userData = '{"Vod":{"StorageLocation":"","UserData":{"IsShowWaterMark":"false","Priority":"7"}}}';
    let hasVideoThumb = 0
    export default {
        components: {
            jAddHref
        },
        props:['showItem'],
        computed: {
            
        },
        data () {
            return {
                imglist: [],
                serIds: [],
                dialogShow: false,
                linkobj: {},
                haslink: false,
                hasvideo: false,
                showVideoDiv: {
                    show: false,
                    file: '',
                    text: '去上传',
                    toLoad: false
                },
                posterimg: '',
                videoprogress: {
                    show: false,
                    num:0
                }
            }
        },
        beforeCreate () {
            
        },
        created () {
        },
        watch: {
            imglist(val) {
                this.$emit('getImgsFn',val)
            },
            linkobj(val) {
                if(val) this.haslink = true
            }
        },
        mounted() {
            
        },
        methods: {
            change(event) {
                this.showVideoDiv.file = ''
                this.showVideoDiv.show = false
                let file = event.target.files[0]
                console.log(file)
                let url = URL.createObjectURL(file); 
                this.showVideoDiv.file = url
                this.getVideoUploadAuth(file)
            },
            // 获取上传视频权限
            getVideoUploadAuth(file) {
                console.log(document.getElementById('file').value)
                // alert('video[value]:'+document.getElementById('file').value)
                let path = document.getElementById('file').value
                let params = {
                    video_title: file.name,
                    video_url: path
                }
                // alert('params:' + params.video_title)
                axios.post(`${xmconfig.API_NC}/aliapi/upload.php`, params).then(res => {
                    // alert('res.data:' + res.data.UploadAuth)
                    uploadAuth = res.data.UploadAuth
                    uploadAddress = res.data.UploadAddress
                    videoId = res.data.VideoId
                    uploader.addFile(file, null, null, null, userData);
                    this.videoprogress.show = true
                    this.videoprogress.num = 0
                    this.videoUploadFn()
                })
            },
            // 上传视频展示的view
            videoUploadFn() {
                uploader.startUpload();
                _videoUploadSuccess.ok = false
                let interval = setInterval(() => {
                    this.videoprogress.num = _uploadprogress
                    if(_videoUploadSuccess.ok) {
                        this.showVideoDiv.show = true
                        this.hasvideo = true
                        this.videoprogress.num = 0
                        this.videoprogress.show = false
                        clearInterval(interval)
                        this.getVideoInfo()
                    }
                }, 10);
            },
            // 获取视频信息
            getVideoInfo() {
                let sett 
                this.$post(`${xmconfig.VIDEO_INFO_URL}/`,{videoId :_videoUploadSuccess.uploadInfo.videoId}).then(res => {
                    res = res.data
                    xmview.showLoading('正在获取缩略图..')
                    if (res.Video.CoverURL) {
                        this.posterimg = res.Video.CoverURL
                        sessionStorage.setItem('video_content',_videoUploadSuccess.uploadInfo.videoId)
                        sessionStorage.setItem('video_thumb',res.Video.CoverURL)
                        xmview.hideLoading()
                        clearTimeout(sett)
                    } else {
                        sett = setTimeout(() => {
                            this.getVideoInfo()
                        }, 3000);
                    }	
                    
                })
            },
            // wx上传
            addimg() {
                let count = this.imglist.length
                let c = 9 - count
                if(c > 0) {
                    //选择图片 或 相机
                    wx.chooseImage({
                        count: c, // 默认9
                        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                        success: function (res) {
                            var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                            syncUpload(localIds);
                        }
                    })
                    let _this = this
                    
                    var syncUpload = function(localIds){
                        var localId = localIds.shift();
                        wx.uploadImage({
                            localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得
                            isShowProgressTips: 1, // 默认为1，显示进度提示
                            success: function (res) {
                                let obj = {}
                                obj.serverId = res.serverId; // 返回图片的服务器端ID
                                // _this.imglist.push(obj)
                                if (window.__wxjs_is_wkwebview) {
                                    wx.getLocalImgData({  //循环调用  getLocalImgData
                                        localId:localId, // 图片的localID
                                        success: function (res) {
                                            var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
                                            localData = localData.replace('jpg', 'jpeg');//iOS 系统里面得到的数据，类型为 image/jgp,因此需要替换一下
                                            obj.base = localData
                                            _this.imglist.push(obj)
                                        }
                                    });
                                } else {
                                    obj.base = localId
                                    _this.imglist.push(obj)
                                }
    
                                if(localIds.length > 0){
                                    window.setTimeout(function(){syncUpload(localIds);}, 1000);
                                    // syncUpload(localIds);
                                }
                            }
                        });
                    }
                }else {
                    xmview.showToast('总数不能超过9张哦')
                }
            },
            // file上传
            onReadImg(file) {
                let filearr = []
                if(typeUtils.isArray(file)) {
                    filearr = file
                }else {
                    filearr.push(file)
                }
                let count = this.imglist.length + filearr.length
                if(count > 9) {
                    xmview.showToast('总数不能超过9张哦')
                }else {
                    let arr = this.imglist
                    filearr.forEach(item => {
                        arr.push(item)
                    });
                    this.imglist = arr
                    // console.log(this.imglist)
                }
                console.log(this.imglist)
            },
            removeimg(index) {
                // alert(this.imglist[index].base)
                let arr = this.imglist
                arr.splice(index,1)
                this.imglist = arr
            },
            addHref(type) {
                if(this.showVideoDiv.file) {
                    this.showVideoDiv.show = true
                }
                if(type === 0) {
                    this.dialogShow = false
                }else {
                    // xmview.showToast('点解了完成哦 去缓存中拿哦！')
                    this.linkobj = JSON.parse(sessionStorage.getItem('linkobj')) 
                    this.dialogShow = false
                }
            }
        },
        
    }
</script>

